/**
 * @author Cheng Liu
 **/

#include "stdafx.h"
#include "EventBus.h"

IMPLEMENT_SINGLETON(EventBus);

using namespace Events;

EventBus::EventBus() {
	//listeners.clear();
	WriteLog("EventBus singleton Created\n");
}

void EventBus::AttachListener( const EventType& type, IEventHandler* handler ) {
	listeners[type].insert(handler);
}

bool EventBus::DettachListener( const EventType& type, IEventHandler* handler ) {
	std::map<EventType, std::set<IEventHandler*> >::iterator itHandlerList = listeners.find(type);
	if (itHandlerList == listeners.end())
		return false;
	std::set<IEventHandler*>::iterator itHandler = itHandlerList->second.find(handler);
	if (itHandler == itHandlerList->second.end())
		return false;

	itHandlerList->second.erase(itHandler);
	return true;
}

void EventBus::ReleaseListener(const IEventHandler* handler ) {
	std::map<EventType, std::set<IEventHandler*> >::iterator itHandlerList;
	for (itHandlerList = listeners.begin(); itHandlerList != listeners.end(); ++itHandlerList) {
		itHandlerList->second.erase((IEventHandler* ) handler);
	}
}

void EventBus::PublishEvent(Event * event ) {
	std::set<IEventHandler*> &HandlerList = listeners[event->GetType()];
	std::set<IEventHandler*>::iterator itHandler;
	for (itHandler = HandlerList.begin(); itHandler != HandlerList.end(); ++itHandler) {
		if ((*itHandler)->HandleEvent(event))
			break;
	}
}
